﻿@*
//------------------------------------------------------------------------------
//  此代码版权声明为全文件覆盖，如有原作者特别声明，会在下方手动补充
//  此代码版权（除特别声明外的代码）归作者本人Diego所有
//  源代码使用协议遵循本仓库的开源协议及附加协议
//  Gitee源代码仓库：https://gitee.com/diego2098/ThingsGateway
//  Github源代码仓库：https://github.com/kimdiego2098/ThingsGateway
//  使用文档：https://diego2098.gitee.io/thingsgateway-docs/
//  QQ群：605534569
//------------------------------------------------------------------------------
*@

@namespace ThingsGateway.Gateway.Blazor
@using System.Linq.Expressions;
@using BlazorComponent;
@using Furion;
@using Mapster;
@using Masa.Blazor
@using Masa.Blazor.Presets;
@using System.IO;
@using Microsoft.AspNetCore.Authorization;

@using ThingsGateway.Admin.Blazor;

@page "/gatewayconfig/collectdevice"
@attribute [Authorize]
@inherits BaseComponentBase
@inject UserResoures UserResoures

@layout MainLayout
@using ThingsGateway.Admin.Core;
@* @if (IsMobile)
{
    @GetAppDataTable()
}
else
{
    <MRow>
        <MCol Md=2 Cols="12">
            <MCard Class="ma-2" Height=@("100%")>
                <MCardTitle>
                    <MTextField Dense Style="max-width:200px;" HideDetails=@("auto") Class="mx-2 my-1" @bind-Value="_searchName"
                                Outlined Label=@typeof(Device).GetDescription(nameof(Device.DeviceGroup)) />
                 </MCardTitle>
                 <MTreeview Style=@($"height: calc(100vh - {BlazorResourceConst.DefaultHeight+100}px);overflow-y:auto")
                          Dense TItem="string" TKey="string" ActiveChanged=@(async a=>
                       {
                       if(_search.DeviceGroup!=a.FirstOrDefault())
                       {
                       _search.DeviceGroup=a.FirstOrDefault();
                       await DatatableQueryAsync();
                       }
                       } )
                            Items="_deviceGroups" ItemText="r=>r" ItemChildren="r=>null"
                            Search="@_searchName"
                          Activatable ItemKey=@(r=>r)>
                     <LabelContent>
                         <span title=@context.Item>
                             @context.Item
                        </span>
                    </LabelContent>
                </MTreeview>
            </MCard>
        </MCol>
        <MCol Md=10 Cols="12">

            @GetAppDataTable()
        </MCol>
    </MRow>
} *@

@GetAppDataTable()


<ImportExcel @ref=_importExcel Import="SaveDeviceImportAsync" Preview="DeviceImportAsync" />

@code {
    RenderFragment GetAppDataTable()
    {
        RenderFragment renderFragment =
    @<AppDataTable @ref="_datatable" AddWidth=@("80%") EditWidth=@("80%") DetailWidth=@("80%")
                       StyleString=@($"height: calc(100vh - {BlazorResourceConst.DefaultHeight+10}px)")
                       TItem="CollectDevice" SearchItem="DevicePageInput"
                       AddItem="DeviceAddInput" EditItem="DeviceEditInput"
                       IsMenuOperTemplate=false SearchModel="@_search"
                       QueryCallAsync="QueryCallAsync" AddCallAsync="AddCallAsync"
                       EditCallAsync="EditCallAsync" DeleteCallAsync="DeleteCallAsync"
                       IsShowDetailButton
                       IsShowQueryButton
                       IsShowAddButton=@UserResoures.IsHasButtonWithRole("gatewaycollectdeviceadd")
                       IsShowDeleteButton=@UserResoures.IsHasButtonWithRole("gatewaycollectdevicedelete")
                       IsShowEditButton=@UserResoures.IsHasButtonWithRole("gatewaycollectdeviceedit")>
        <AddTemplate>
            @GetRenderFragment(context)
        </AddTemplate>

        <EditTemplate>
            @GetRenderFragment(context)

        </EditTemplate>

        <SearchTemplate>
            <MTextField Dense
                        Style="max-width:200px;" HideDetails=@("auto") Class="my-1  mx-2 " @bind-Value="context.Name"
                        Clearable
                        Outlined
                        Label=@context.Description(x => x.Name) />
            <MTextField Dense
                        Style="max-width:200px;" HideDetails=@("auto") Class="my-1  mx-2 " @bind-Value="context.PluginName"
                        Clearable
                        Outlined
                        Label=@context.Description(x => x.PluginName) />
            <MTextField Dense
                        Style="max-width:200px;" HideDetails=@("auto") Class="my-1  mx-2 " @bind-Value="context.DeviceGroup"
                        Clearable
                        Outlined
                        Label=@context.Description(x => x.DeviceGroup) />
        </SearchTemplate>
        <OtherToolbarTemplate>

            <MMenu OffsetY
                   Context="menu">
                <ActivatorContent>
                    <MButton @attributes="@menu.Attrs" Color="primary"
                             Class="my-1  mx-2 ">
                        复制
                        <AppChevronDown></AppChevronDown>
                    </MButton>
                </ActivatorContent>
                <ChildContent>
                    <MList>
                        <MListItem OnClick="()=>CopyDeviceAsync(context)">复制设备</MListItem>
                        <MListItem OnClick="()=>CopyDevAndVarAsync(context)">复制设备及设备下变量</MListItem>
                    </MList>

                </ChildContent>
            </MMenu>


                  <MMenu OffsetY
                   Context="menu">
                <ActivatorContent>
                    <MButton @attributes="@menu.Attrs" Color="primary"
                             Class="my-1  mx-2 ">
                        同步属性
                        <AppChevronDown></AppChevronDown>
                    </MButton>
                </ActivatorContent>
                <ChildContent>
                    <MList>
                        <MListItem OnClick="()=>GetDriverProperties(context.ToList())">同步所选项的设备属性</MListItem>
                        <MListItem OnClick="()=>GetDriverProperties(null)">同步全部设备属性</MListItem>
                    </MList>

                </ChildContent>
            </MMenu>

            <MMenu OffsetY
                   Context="menu">
                <ActivatorContent>
                    <MButton @attributes="@menu.Attrs" Color="primary"
                             Class="my-1  mx-2 ">
                        导出
                        <AppChevronDown></AppChevronDown>
                    </MButton>
                </ActivatorContent>
                <ChildContent>
                    <MList>
                        <MListItem OnClick="()=>DownExportAsync()">导出全部</MListItem>
                        <MListItem OnClick="()=>DownExportAsync(_search)">导出搜索项</MListItem>
                    </MList>

                </ChildContent>
            </MMenu>


           

            <MButton Disabled=@(!UserResoures.IsHasButtonWithRole("gatewaycollectdeviceedit")) Class="my-1  mx-2" OnClick="()=>{ _importExcel.Step=1;  _importExcel.IsShowImport=true;}" Color="primary">
                导入
            </MButton>
        </OtherToolbarTemplate>

        <ItemColTemplate>
            @switch (context.Header.Value)
        {

        case nameof(context.Item.Enable):
            <EnableChip Value="context.Item.Enable">
            </EnableChip>
        break;

        case nameof(context.Item.PluginName):
            @context.Value?.ToString().GetFileNameAndTypeName().Item2
        break;

        default:
            @if (context.Header.CellClass?.Contains("text-truncate") == true)
        {
            <span title=@context.Value>
                @context.Value
            </span>
        }
        else
        {
            @context.Value
        }
        break;

        }

        </ItemColTemplate>


    </AppDataTable>
    ;
        return renderFragment;
    }
}
@code {

    RenderFragment GetRenderFragment(DeviceAddInput context)
    {
        RenderFragment renderFragment =
    @<div>
        <div class="mt-3">
            <span class="ml-1  font-weight-black">基础属性设置</span>
        </div>

        <MRow Class="mt-3">
            <MCol Md=3 Sm=12>
                <MTextField Dense Outlined HideDetails="@("auto")" Color="primary" @bind-Value=@context.Name Label="@(context.Description(x => x.Name))" />
            </MCol>
            <MCol Md=3 Sm=12>
                <MTextField Dense Outlined HideDetails="@("auto")" Color="primary" @bind-Value=@context.Description Label="@(context.Description(x => x.Description))" />
            </MCol>
            <MCol Md=3 Sm=12>
                <MTextField Dense Outlined HideDetails="@("auto")" Color="primary" @bind-Value=@context.DeviceGroup Label="@(context.Description(x => x.DeviceGroup))" />
            </MCol>

        </MRow>
        <div class="mt-3">
            <span class="ml-1  font-weight-black">插件选择</span>
        </div>
        <MRow Class="mt-3">
            <MCol Md=3 Sm=12>

                <MCascader Value="context.PluginName" Clearable TValue=string TItem="DriverPlugin" Outlined
                           ValueChanged=@(async a=>await DriverValueChangedAsync(context,a)) Label="@(typeof(CollectDeviceRunTime).GetDescription(nameof(CollectDeviceRunTime.PluginName)))"
                           Items="_driverPlugins" ItemText="u => u.Name" ItemValue="u => u.FullName" ItemChildren="u => u.Children"
                           MenuProps="@(props => { props.Auto = true; props.OffsetY = true; })"
                           ShowAllLevels="false" HideDetails="@("auto")" Height="30" Dense>
                </MCascader>

            </MCol>
            <MCol Md=3 Sm=12>
                <MSelect @bind-Value=@context.Enable Outlined Color="primary"
                         Items=@(new List<bool>(){true,false}) Label="@context.Description(x=>x.Enable)"
                         MenuProps="@(props => { props.Bottom = true; props.OffsetY = true; })"
                         ItemText=@((u) =>u.ToString()) ItemValue=@(u =>u)
                         HideDetails=@("auto") Height="30" Dense>
                </MSelect>

            </MCol>
            <MCol Md=3 Sm=12>
                <MSelect @bind-Value=@context.IsLogOut Outlined Color="primary"
                         Items=@(new List<bool>(){true,false}) Label="@context.Description(x=>x.IsLogOut)"
                         MenuProps="@(props => { props.Bottom = true; props.OffsetY = true; })"
                         ItemText=@((u) =>u.ToString()) ItemValue=@(u =>u)
                         HideDetails=@("auto") Height="30" Dense>
                </MSelect>
            </MCol>

            <MCol Md=3 Sm=12>
                <MTextField Dense Outlined HideDetails="@("auto")" Color="primary" @bind-Value=@context.IntervalTime Label="@(context.Description(x => x.IntervalTime))" />
            </MCol>

        </MRow>
        <div class="mt-3">
            <span class="ml-1  font-weight-black">冗余配置</span>
        </div>
        <MRow Class="mt-3">
            <MCol Md=3 Sm=12>

                <MSelect @bind-Value=@context.IsRedundant Outlined Color="primary"
                         Items=@(new List<bool>(){true,false}) Label="@context.Description(x=>x.IsRedundant)"
                         MenuProps="@(props => { props.Bottom = true; props.OffsetY = true; })"
                         ItemText=@((u) =>u.ToString()) ItemValue=@(u =>u)
                         HideDetails=@("auto") Height="30" Dense>
                </MSelect>
            </MCol>

            <MCol Md=3 Sm=12>
                <MSelect Class="mr-3" @bind-Value=@context.RedundantDeviceId Outlined
                         Items=@(_devices) Label="@context.Description(x=>x.RedundantDeviceId)"
                         MenuProps="@(props => { props.Bottom = true; props.OffsetY = true; })"
                         ItemText=@((u) =>u.Name) ItemValue=@(u =>u.Id)
                         ItemDisabled="u => (u.PluginName!=context.PluginName||u.Id==context.Id)"
                         HideDetails=@("auto") Height="30" Dense>
                </MSelect>
            </MCol>

        </MRow>


        <div class="mt-3">
            <span class="ml-1  font-weight-black">插件属性配置</span>
        </div>

        <MRow Class="mt-3">
            <MCol Md=3 Sm=12>
                <MButton OnClick=@(async() =>
                     {
                     if(!context.PluginName.IsNullOrEmpty())
                     {
                     context.DevicePropertys= GetDriverProperties(context.PluginName,context.Id);
                     }
                     else
                     {
                     await PopupService.EnqueueSnackbarAsync("需选择插件",AlertTypes.Warning);
                     }
                     }
                     ) Color="primary">
                    刷新设备属性
                </MButton>
            </MCol>
        </MRow>

        @if (context.DevicePropertys != null)
    {
        <MRow Class="mt-3">
            @foreach (var item in context.DevicePropertys)
        {
        int md=3;
            @if (item.PropertyName.Contains("BigText"))
        {
        md=12;
        }
            <MCol Md=md Sm=12 Class="my-2">
                <MTooltip Disabled=@(item.Remark==null||item.Remark?.IsNullOrEmpty()==true) Bottom Context="tip">
                    <ActivatorContent>
                        @if (item.PropertyName.Contains("BigText"))
                    {
                        <MTextarea MinHeight="100" AutoGrow @attributes="@tip.Attrs" Color="primary"
                                   Dense Outlined HideDetails="@("auto")" @bind-Value=@item.Value Label="@item.Description" />
                    }
                    else
                    {
                        <MTextField Type="@(item.PropertyName.Contains("Password") ? "password" : "text")" @attributes="@tip.Attrs" Color="primary"
                                    Dense Outlined HideDetails="@("auto")" @bind-Value=@item.Value Label="@item.Description" />
                    }
                    </ActivatorContent>
                    <ChildContent>
                        <span>@item.Remark</span>
                    </ChildContent>
                </MTooltip>
            </MCol>
        }

        </MRow>
    }

    </div>
    ;
        return renderFragment;
    }

}
